package controller

import (
	"gitee.com/saxon134/sysmain/aliyun"
	"gitee.com/saxon134/sysmain/api"
	"gitee.com/saxon134/sysmain/db"
	"gitee.com/saxon134/sysmain/db/models"
	"gitee.com/saxon134/sysmain/errs"
	"github.com/saxon134/go-utils/saData"
	"net/http"
	"strings"
)

func GetResources(w http.ResponseWriter, r *http.Request) {
	if db.MySql == nil {
		api.ResSuccess(w, nil)
		return
	}

	if checkSign(r) == false {
		api.ResError(w, errs.ErrorUnauthorized.String())
		return
	}

	var ary = make([]*models.TblResource, 0, 10)
	var conn = db.MySql.Table(models.TBNResource).Where("status > -1")
	t, _ := saData.ToInt(r.URL.Query().Get("type"))
	if t > 0 {
		conn.Where("`type` = ?", t)
	}
	conn.Find(&ary)
	api.ResSuccess(w, ary)
}

func SyncAliyunEcsList(w http.ResponseWriter, r *http.Request) {
	err := aliyun.SyncAliYunEcsList()
	if err != nil {
		api.ResError(w, err.Error())
		return
	}
	api.ResSuccess(w, nil)
}

func SyncAliyunEcsMonitor(w http.ResponseWriter, r *http.Request) {
	idAry := strings.Split(r.URL.Query().Get("instanceIds"), ",")
	var response = map[string]interface{}{}
	for _, id := range idAry {
		data, _ := aliyun.SyncAliYunEcsMonitorData(id)
		if data != nil {
			response[id] = data
		}
	}
	api.ResSuccess(w, response)
}
